//
//  UPGridItem.m
//  Uang Pasti
//
//  Created by 李永彬 on 2025/8/18.
//

#import "UPGridItem.h"
#import <Masonry/Masonry.h>

@implementation UPGridItem

- (instancetype)initWithImage:(UIImage *)image title:(NSString *)title {
    self = [super init];
    if (self) {
        // 1. 背景图片（关键：根据图片宽高比设置约束）
        _backgroundImageView = [[UIImageView alloc] initWithImage:image];
        _backgroundImageView.contentMode = UIViewContentModeScaleAspectFill;
        _backgroundImageView.clipsToBounds = YES;
        [self addSubview:_backgroundImageView];
        
        // 2. 标题（固定在底部）
        _titleLabel = [[UILabel alloc] init];
        _titleLabel.text = title;
        _titleLabel.textColor = [UIColor colorWithHexString:@"000000"];
        _titleLabel.textAlignment = NSTextAlignmentCenter;
        _titleLabel.font = [UIFont systemFontOfSize:15 weight:UIFontWeightSemibold];
        [self addSubview:_titleLabel];
        
        _button = [UIButton buttonWithType:UIButtonTypeSystem];
        [_button setBackgroundImage:[UIImage imageNamed:@"button_bg_style3"] forState:UIControlStateNormal];
//        _button.userInteractionEnabled = NO;
        [self addSubview:_button];
        
        [_backgroundImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self);
        }];
        
        [_titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.leading.trailing.equalTo(self);
            make.height.equalTo(@30);
            make.centerY.equalTo(self).offset(20);
        }];
        
        CGFloat height = 36.0;
        CGFloat aspectRatio = 224 / 75.0;
        CGFloat width = height * aspectRatio;
        [_button mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(width);
            make.height.mas_equalTo(height);
            make.centerX.equalTo(self);
            make.bottom.equalTo(self).offset(-10);
        }];
        
        if (image) {
            CGFloat aspectRatio = image.size.width / image.size.height;
            [_backgroundImageView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.width.equalTo(_backgroundImageView.mas_height).multipliedBy(aspectRatio);
            }];
        }
        
        [self setContentHuggingPriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisVertical];
    }
    return self;
}

@end
